import { ref, reactive } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { USER_API } from '../api/config'
import { regionData } from 'element-china-area-data'

interface Address {
  id: number
  contactName: string
  phone: string
  province: string
  city: string
  district: string
  street: string
  isDefault: boolean
}

interface AddressForm {
  id: number
  contactName: string
  phone: string
  region: string[]
  province: string
  city: string
  district: string
  street: string
  isDefault: boolean
}

export function useAddress() {
  const addresses = ref<Address[]>([])
  const addressesLoading = ref(false)
  const isEditingAddress = ref(false)

  // 地址表单
  const addressForm = reactive<AddressForm>({
    id: 0,
    contactName: '',
    phone: '',
    region: [],
    province: '',
    city: '',
    district: '',
    street: '',
    isDefault: false
  })

  // 地址表单验证规则
  const addressRules = {
    contactName: [
      { required: true, message: '请输入收货人姓名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    region: [
      { required: true, message: '请选择所在地区', trigger: 'change' }
    ],
    street: [
      { required: true, message: '请输入详细地址', trigger: 'blur' },
      { min: 3, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
    ]
  }

  // 省市区数据
  const regionOptions = regionData

  // 格式化地址
  const formatAddress = (address: Address) => {
    return `${address.province} ${address.city} ${address.district} ${address.street}`
  }

  // 重置地址表单
  const resetAddressForm = () => {
    addressForm.id = 0
    addressForm.contactName = ''
    addressForm.phone = ''
    addressForm.region = []
    addressForm.province = ''
    addressForm.city = ''
    addressForm.district = ''
    addressForm.street = ''
    addressForm.isDefault = false
  }

  // 获取收货地址列表
  const fetchAddresses = async () => {
    try {
      addressesLoading.value = true
      const response = await axios.get(USER_API.ADDRESS_LIST)
      
      if (Array.isArray(response.data)) {
        addresses.value = response.data.map((addr: any) => ({
          id: addr.id,
          contactName: addr.contactName,
          phone: addr.phone,
          province: addr.province,
          city: addr.city,
          district: addr.district,
          street: addr.street,
          isDefault: addr.isDefault,
          fullAddress: `${addr.province} ${addr.city} ${addr.district} ${addr.street}`
        }))
      } else {
        addresses.value = []
      }
    } catch (error) {
      console.error('获取地址列表失败:', error)
      ElMessage.error('获取地址列表失败')
    } finally {
      addressesLoading.value = false
    }
  }

  // 添加新地址
  const addNewAddress = () => {
    isEditingAddress.value = false
    resetAddressForm()
    return true
  }

  // 编辑地址
  // 添加反向编码函数（移到return之前）
  const getRegionCodesByNames = (provinceName: string, cityName: string, districtName: string): string[] => {
    const codes: string[] = []
    
    // 查找省份编码
    const province = regionData.find((p: any) => p.label === provinceName)
    if (!province) return []
    codes.push(province.value)
    
    // 查找城市编码
    const city = province.children?.find((c: any) => c.label === cityName)
    if (!city) return codes
    codes.push(city.value)
    
    // 查找区县编码
    const district = city.children?.find((d: any) => d.label === districtName)
    if (!district) return codes
    codes.push(district.value)
    
    return codes
  }

  // 编辑地址
  const editAddress = (address: Address) => {
    isEditingAddress.value = true
    
    addressForm.id = address.id
    addressForm.contactName = address.contactName
    addressForm.phone = address.phone
    
    // 使用反向编码获取省市区编码
    const regionCodes = getRegionCodesByNames(address.province, address.city, address.district)
    addressForm.region = regionCodes
    
    addressForm.province = address.province
    addressForm.city = address.city
    addressForm.district = address.district
    addressForm.street = address.street
    addressForm.isDefault = address.isDefault || false
    
    return true
  }

  // 保存地址
  const saveAddress = async () => {
    try {
      // 从级联选择器的编码值中获取对应的名称
      if (addressForm.region && addressForm.region.length === 3) {
        const [provinceCode, cityCode, districtCode] = addressForm.region
        
        // 根据编码获取名称
        const province = regionData.find((p: any) => p.value === provinceCode)
        const city = province?.children?.find((c: any) => c.value === cityCode)
        const district = city?.children?.find((d: any) => d.value === districtCode)
        
        addressForm.province = province?.label || ''
        addressForm.city = city?.label || ''
        addressForm.district = district?.label || ''
      }
      
      const submitData = {
        id: addressForm.id,
        contactName: addressForm.contactName,
        phone: addressForm.phone,
        province: addressForm.province,
        city: addressForm.city,
        district: addressForm.district,
        street: addressForm.street,
        isDefault: addressForm.isDefault || false
      }
      
      if (isEditingAddress.value) {
        await axios.put(`${USER_API.UPDATE_ADDRESS}/${addressForm.id}`, submitData)
        ElMessage.success('地址更新成功')
      } else {
        await axios.post(USER_API.ADD_ADDRESS, submitData)
        ElMessage.success('地址添加成功')
      }
      
      await fetchAddresses()
      return true
    } catch (error) {
      console.error('保存地址失败:', error)
      ElMessage.error('保存地址失败，请稍后重试')
      return false
    }
  }

  // 设为默认地址
  const setAsDefault = async (address: Address) => {
    try {
      await axios.patch(`${USER_API.ADDRESS_DEFAULT}/${address.id}/default`)
      ElMessage.success('默认地址设置成功')
      await fetchAddresses()
    } catch (error) {
      console.error('设置默认地址失败:', error)
      ElMessage.error('设置默认地址失败，请稍后重试')
    }
  }

  // 确认删除地址
  const confirmDeleteAddress = (address: Address) => {
    return ElMessageBox.confirm(
      '确定要删除该收货地址吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      return deleteAddress(address.id)
    })
  }

  // 删除地址
  const deleteAddress = async (addressId: number) => {
    try {
      await axios.delete(`${USER_API.DELETE_ADDRESS}/${addressId}`)
      ElMessage.success('地址删除成功')
      await fetchAddresses()
    } catch (error) {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败，请稍后重试')
    }
  }

  // 填充地址信息（用于定位）
  const fillAddressInfo = (locationData: any) => {
    if (locationData) {
      addressForm.province = locationData.province
      addressForm.city = locationData.city
      addressForm.district = locationData.district
      addressForm.street = locationData.street
      addressForm.region = locationData.region
      
      ElMessage.success('定位成功，地址信息已自动填充')
    }
  }

  return {
    addresses,
    addressesLoading,
    isEditingAddress,
    addressForm,
    addressRules,
    regionOptions,
    formatAddress,
    resetAddressForm,
    fetchAddresses,
    addNewAddress,
    editAddress,
    saveAddress,
    setAsDefault,
    confirmDeleteAddress,
    fillAddressInfo,
    getRegionCodesByNames // 现在可以正确导出了
  }
}